package br.com.ldml2;

import java.util.ArrayList;
import java.util.LinkedList;

import br.com.ldml.Tripla;
import br.com.tmp.Temp;
import br.com.util.Escritor;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

@XStreamAlias("retrieve")
public class Retrieve implements LdmlCommand {
	@XStreamAsAttribute
	private String uri, endpoint;
	
	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}
	
	public String getEndpoint() {
		return endpoint;
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	@Override
	public void exec(String tmpFileName) {
		System.out.println("Retrieve.exec();");
		ArrayList<Tripla> t = new ArrayList<Tripla>();
		
		//sparql query
		String sparqlQueryString = 					
				"SELECT DISTINCT ?a ?b WHERE { ?a ?b <"+ uri +"> } LIMIT 100";
		
		//endpoint config
		Query query = QueryFactory.create(sparqlQueryString);
		QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query);

		//print result
		ResultSet results = qexec.execSelect();
		for(QuerySolution qs : ResultSetFormatter.toList(results)) {
			Tripla t1 = new Tripla(qs.get("a").toString(), qs.get("b").toString(), uri);	
			t.add(t1);
		}

		//closing connection
		qexec.close() ;
		
		Tripla[] aux = new Tripla[t.size()];
		aux = t.toArray(aux);
		
		
		//TODO salvar em arquivo, num formato que a EMML leia
		LinkedList<Tripla> ll = new LinkedList<Tripla>();
		for(Tripla a1 : aux) ll.add(a1);
		Temp tmp = new Temp();
		tmp.setTriplas(ll);
		
		XStream xs = new XStream();
		Escritor e = new Escritor();
		e.abreArquivo(tmpFileName, true);
		e.gravaArquivo(new String[] { xs.toXML(tmp) } );
		
		e.fechaArquivo();
	}
}
